﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using StudentInfoSystem.Core.Data.DbContexts;
using StudentInfoSystem.Core.Interfaces;
using StudentInfoSystem.Core.MockImplementations;
using StudentInfoSystem.UI.Services;
using StudentInfoSystem.UI.ViewModels;
using StudentInfoSystem.UI.Views;
using StudentInfoSystem.Core.Models;
using System.Windows.Navigation;

namespace StudentInfoSystem.UI;

public class Bootstrapper
{
    public static IHost AppHost { get; private set; }

    public Bootstrapper()
    {
        // 依赖注入  单例模式
        AppHost = Host.CreateDefaultBuilder().UseSerilog()
            .ConfigureServices((context, services) =>
            {
                // 注册 AppDbContext 为 Scoped（每次请求一个实例）
                services.AddScoped<AppDbContext>(provider =>
                {
                    var settings = provider.GetRequiredService<AppSettings>();
                    return new AppDbContext($"Data Source={settings.SavedDataBasePath}");
                });

                // 注册学生服务
                services.AddScoped<StudentService>(); // 改为 Scoped 生命周期
                services.AddScoped<IStudentService>(provider => provider.GetRequiredService<StudentService>());

                // 注册统计服务
                services.AddSingleton<MockStatisticsService>();
                services.AddSingleton<IStatisticsService, MockStatisticsService>();

                // 注册设置
                services.AddSingleton<AppSettings>(_ => AppSettings.Instance);

                // 添加自动保存服务
                services.AddSingleton<AutoSaveService>();
                services.AddSingleton<IHostedService>(provider => provider.GetRequiredService<AutoSaveService>());

                // 注册视图模型
                //services.AddSingleton<MainWindowViewModel>();
                services.AddSingleton<StudentListViewModel>();
                // 添加其他需要的ViewModel
            })
            .Build();
    }

    // 启动后台服务
    public void Start()
    {
        AppHost.StartAsync().GetAwaiter().GetResult(); // 启动主机
    }
    // 停止后台服务
    public void Stop()
    {
        Log.Information("正在停止应用程序...");
        AppHost.StopAsync().GetAwaiter().GetResult();
    }
}